package com.qb.service.impl;

import com.qb.mapper.*;
import com.qb.pojo.*;
import com.qb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")//业务层
@Transactional//开启事务管理器
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private RoleMapper roleMapper;

    //登录
    @Override
    public User login(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUnameEqualTo(user.getUname());
        criteria.andUpassEqualTo(user.getUpass());
        List<User> users = userMapper.selectByExample(userExample);
        //判断该账户是否存在，如果存在获取该账户并返回
        if (users != null && users.size() > 0) {
            return users.get(0);
        } else {
            return null;
        }
    }
    //查询用户列表

    @Override
    public List<User> findAll() {
        return userMapper.selectByExample(null);
    }
    //根据ID删除用户

    @Override
    public boolean deleteByUid(Integer uid) {
        //删除和user表相关的表数据  删除博客信息
        BlogExample blogExample = new BlogExample();
        blogExample.createCriteria().andUFkEqualTo(uid);
        blogMapper.deleteByExample(blogExample);
        //删除评论信息
        EvaluateExample evaluateExample = new EvaluateExample();
        evaluateExample.createCriteria().andUFkEqualTo(uid);
        evaluateMapper.deleteByExample(evaluateExample);
        //删除该uid的相关数据
        return userMapper.deleteByPrimaryKey(uid) > 0 ? true : false;
    }
    //模糊查询

    @Override
    public List<User> findByUname(String uname) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUnameLike("%" + uname + "%");
        List<User> users = userMapper.selectByExample(userExample);
        return users;
    }
    //详情

    @Override
    public Map<String, Object> findUser(Integer uid) {
        User user = userMapper.selectByPrimaryKey(uid);
        Role role = roleMapper.selectByPrimaryKey(user.getUtype());
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("role", role);
        return map;
    }
}
